import { useHttp } from "./useHttp";
import { QueryKey, useMutation, useQuery } from "react-query";
import { Billboard } from "../types/billboard";
import {
  useAddConfig,
  useDeleteConfig,
  useKanbanReorderConfig,
} from "./useOptimisticConfig";

export const useBillboards = (params: Partial<Billboard>) => {
  const client = useHttp();
  return useQuery<Billboard[]>(["kanbans", params], () =>
    client("kanbans", { data: params })
  );
};

export const useAddBillboard = (queryKey: QueryKey) => {
  const client = useHttp();
  return useMutation(
    (params: Partial<Billboard>) =>
      client("kanbans", { method: "POST", data: params }),
    useAddConfig(queryKey)
  );
};

export const useDeleteBillboard = (queryKey: QueryKey) => {
  const client = useHttp();
  return useMutation(
    ({ id }: { id: number }) => client(`kanbans/${id}`, { method: "DELETE" }),
    useDeleteConfig(queryKey)
  );
};

export interface SortProps {
  // 需要重新排序的 item
  fromId: number;
  // 目标 item
  referenceId: number | undefined;
  // 放在目标 item 的前或后
  type: "before" | "after";
  fromKanbanId?: number;
  toKanbanId?: number;
}

export const useReorderBillboard = (queryKey: QueryKey) => {
  const client = useHttp();
  return useMutation(
    (params: SortProps) =>
      client("kanbans/reorder", {
        data: params,
        method: "POST",
      }),
    useKanbanReorderConfig(queryKey)
  );
};
